/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * 
 * 
 * Description: This activity displays a search box and initiates catalog searches. It also is responsible for
 * 				handling ISBN barcode scan searches.
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.List;

import com.google.analytics.tracking.android.EasyTracker;


import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.item.SearchResultTitle;
import us.in.lib.acpl.Mobile_ACPL.location.LocationInfo;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseActivity;
import us.in.lib.acpl.Mobile_ACPL.ws.MainSearchHandler;
import us.in.lib.acpl.Mobile_ACPL.ws.SearchCatalogHandler;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SearchActivity extends BaseActivity {

	private String searchTypeFilter = null;
	private String searchLibraryFilter = null;
	private String materialTypeFilter = null;
	private MainSearchHandler handler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		this.getActionBar().setTitle("  Search Catalog");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);
		handler = new MainSearchHandler(this);
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
		// Register listeners
		Mobile_ACPL app = (Mobile_ACPL) this.getApplication();
		app.setSearchHandler(handler);
		findViewById(R.id.scanButton).setOnClickListener(new ScanListener());
		findViewById(R.id.searchButton).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View view) {

						search();
					}

				});

		findViewById(R.id.searchBox).setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View view, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_ENTER
						&& event.getAction() == KeyEvent.ACTION_UP) {
					search();
				}
				return false;
			}

		});

		// Set up spinners
		Spinner spinner = (Spinner) findViewById(R.id.searchTypeSelector);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter
				.createFromResource(this, R.array.searchTypes,
						android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new SearchTypeListener());

		spinner = (Spinner) findViewById(R.id.searchLibrarySelector);
		adapter = ArrayAdapter.createFromResource(this,
				R.array.libraryLocationsPlusAll,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new LibraryFilterListener());

		spinner = (Spinner) findViewById(R.id.materialTypeSelector);
		adapter = ArrayAdapter.createFromResource(this, R.array.materialTypes,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new MaterialTypeListener());

	}
	
	  @Override
	  public void onStart() {
	    super.onStart();
	    EasyTracker.getInstance().activityStart(this); // Add this method.
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	    EasyTracker.getInstance().activityStop(this); // Add this method.
	  }

	public void search() {

		TextView t = (TextView) findViewById(R.id.searchBox);

		if (t.getText() == null || t.getText().toString().equals("")) {
			Toast toast = Toast.makeText(this, "Please enter a search term",
					Toast.LENGTH_SHORT);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		} else {

			EasyTracker.getTracker().sendEvent("Search", "Search Button Pressed", null, null);
			findViewById(R.id.searchButton).setVisibility(View.GONE);
			findViewById(R.id.searchBar).setVisibility(View.VISIBLE);

			handler.search(t.getText().toString(),
					SearchCatalogHandler.RESULTS_PER_PAGE, searchTypeFilter,
					searchLibraryFilter, materialTypeFilter);

		}
	}

	public void handleSearchResults(List<SearchResultTitle> results) {

		Intent intent = new Intent(this, SearchResultsActivity.class);
		intent.putExtra("source", "SearchActivity");
		startActivity(intent);

	}

	private class SearchTypeListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			if (view != null) {
				TextView t = (TextView) view;
				String text = (String) t.getText();

				if (text.equalsIgnoreCase("General")) {
					searchTypeFilter = null;
				} else {
					searchTypeFilter = text;
				}

			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}

	}

	private class LibraryFilterListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {

			if (view != null) {
				TextView t = (TextView) view;
				String text = (String) t.getText();

				if (text.equalsIgnoreCase("All")) {
					searchLibraryFilter = null;
				} else {
					searchLibraryFilter = LocationInfo.getSystemName(text);
				}

			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}

	}

	private class MaterialTypeListener implements OnItemSelectedListener {

		@Override
		public void onItemSelected(AdapterView<?> viewParent, View view,
				int position, long id) {
			if (view != null) {
				TextView t = (TextView) view;
				String text = (String) t.getText();

				if (text.equalsIgnoreCase("All")) {
					materialTypeFilter = null;
				} else {
					materialTypeFilter = text;
				}

			}

		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub

		}

	}

	private class ScanListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			
			
			if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)
					&&getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_AUTOFOCUS)){
				findViewById(R.id.scanArrow).setVisibility(View.GONE);
				findViewById(R.id.scanBar).setVisibility(View.VISIBLE);
				Intent intent = new Intent("com.google.zxing.client.android.SCAN");
				intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
				intent.putExtra("SCAN_FORMATS", "EAN_13");
				startActivityForResult(intent, 0);
			}else{
				Toast toast = Toast.makeText(arg0.getContext(), "This feature is not available for your device. \n" +
						"\nA rear-facing camera with autofocus is required.",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}


		}

	}

	@Override
	public void onResume() {
		super.onResume();
		findViewById(R.id.scanButton).setVisibility(View.VISIBLE);
		findViewById(R.id.searchButton).setVisibility(View.VISIBLE);
		findViewById(R.id.searchBar).setVisibility(View.GONE);

		findViewById(R.id.scanArrow).setVisibility(View.VISIBLE);
		findViewById(R.id.scanBar).setVisibility(View.GONE);
		
	
	
		
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == 0) {
			if (resultCode == RESULT_OK) {
				
			
				EasyTracker.getTracker().sendEvent("Search", "ISBN Barcode Scanned", null, null);
				
				String contents = intent.getStringExtra("SCAN_RESULT");
				String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

				findViewById(R.id.scanButton).setVisibility(View.GONE);
				findViewById(R.id.scanArrow).setVisibility(View.GONE);
				findViewById(R.id.scanBar).setVisibility(View.VISIBLE);

				handler.search(contents, SearchCatalogHandler.RESULTS_PER_PAGE,
						"isbn", null, null);

			} else if (resultCode == RESULT_CANCELED) {
				Toast toast = Toast.makeText(this, "Scan failed.",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
		}
	}

}
